<template>
  <!-- 使用 v-if 指令来控制组件的渲染与销毁 -->
  <div v-if="show" class="chat-window">
    <!-- 聊天窗口头部 -->
    <div class="chat-header">
      <h3>在线客服</h3>
      <button class="close-btn" @click="closeChatWindow">&times;</button>
    </div>
    <!-- 聊天消息显示区域 -->
    <div class="chat-messages">
      <div
          v-for="(message, index) in chatMessages"
          :key="index"
          :class="{ 'user-message': message.sender === 'user', 'agent-message': message.sender === 'agent' }"
      >
        <span>{{ message.text }}</span>
      </div>
    </div>
    <!-- 输入框和发送按钮 -->
    <div class="chat-input">
      <input
          v-model="newMessage"
          type="text"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
      />
      <button @click="sendMessage" :disabled="!ws || ws.readyState !== 1">
        {{ (!ws || ws.readyState !== 1) ? '连接中...' : '发送' }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

// 定义props和emits
interface Props {
  show: boolean;
}

interface Emits {
  (e: 'update:show', value: boolean): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 存储聊天消息的数组
const chatMessages = ref([
  { sender: 'agent', text: '您好，有什么可以帮助您？' }
]);

// 新消息输入框的值
const newMessage = ref('');

const userId = localStorage.getItem('userId') || 'guest';
const serviceId = '1'; // 管理员id
let ws: WebSocket | null = null;
let reconnectTimer: any = null;

function getWSUrl() {
  let token = '';
  try {
    token = localStorage.getItem('token') || '';
  } catch {}
  if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
    return `ws://localhost:666/chat?token=${token}`;
  } else {
    return `ws://${window.location.host}/chat?token=${token}`;
  }
}

function connectWS() {
  let token = localStorage.getItem('token');
  if (!token) {
    alert('请先登录后再使用在线客服功能！');
    return;
  }
  ws = new WebSocket(getWSUrl());
  ws.onopen = () => {
    console.log('WebSocket已连接');
    chatMessages.value.push({ sender: 'agent', text: '客服已上线，欢迎咨询！' });
  };
  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      if (data.type && data.content) {
        chatMessages.value.push({ sender: data.from === userId ? 'user' : 'agent', text: data.content });
      }
    } catch (e) {}
  };
  ws.onclose = () => {
    chatMessages.value.push({ sender: 'agent', text: '连接已断开，正在尝试重连...' });
    // 自动重连
    reconnectTimer = setTimeout(connectWS, 2000);
  };
}
onMounted(() => {
  connectWS();
});
onUnmounted(() => {
  ws && ws.close();
  if (reconnectTimer) clearTimeout(reconnectTimer);
});

// 关闭聊天窗口
const closeChatWindow = () => {
  emit('update:show', false);
  ws && ws.close();
  if (reconnectTimer) clearTimeout(reconnectTimer);
};

// 发送消息的方法
const sendMessage = () => {
  if (!ws || ws.readyState !== 1) {
    alert('正在连接服务器，请稍后再试');
    return;
  }
  if (newMessage.value.trim()) {
    const msg = {
      type: 'info',
      content: newMessage.value,
      to: serviceId
    };
    ws.send(JSON.stringify(msg));
    // 不要本地 push，等服务端回消息
    newMessage.value = '';
  }
};
</script>

<style scoped>
.chat-window {
  width: 350px;
  height: 500px;
  border: 1px solid #ccc;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(80, 80, 120, 0.12);
  background-color: #fff;
  position: fixed;
  right: 40px;
  bottom: 100px;
  z-index: 2001;
  transition: box-shadow 0.2s, width 0.2s, height 0.2s;
}
@media (max-width: 900px) {
  .chat-window {
    width: 90vw;
    height: 60vh;
    right: 5vw;
    bottom: 60px;
    min-width: 240px;
    min-height: 320px;
  }
}
@media (max-width: 600px) {
  .chat-window {
    width: 100vw;
    height: 100vh;
    right: 0;
    bottom: 0;
    border-radius: 0;
    max-width: 100vw;
    max-height: 100vh;
  }
}

.chat-header {
  padding: 14px 20px;
  background: linear-gradient(90deg, #4f8cff 0%, #6ee7b7 100%);
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chat-header h3 {
  margin: 0;
  font-size: 18px;
  color: #fff;
  letter-spacing: 1px;
}
.close-btn {
  background: none;
  border: none;
  font-size: 22px;
  color: #fff;
  cursor: pointer;
  transition: color 0.2s;
}
.close-btn:hover {
  color: #333;
}

.chat-messages {
  flex: 1;
  padding: 18px 16px;
  overflow-y: auto;
  background: #f8fafc;
  scrollbar-width: thin;
  scrollbar-color: #cbd5e1 #f1f5f9;
}
.chat-messages::-webkit-scrollbar {
  width: 6px;
}
.chat-messages::-webkit-scrollbar-thumb {
  background-color: #e0e7ef;
  border-radius: 6px;
}
.user-message,
.agent-message {
  margin-bottom: 14px;
  padding: 10px 16px;
  border-radius: 16px;
  max-width: 80%;
  line-height: 1.5;
  font-size: 15px;
  word-break: break-all;
  box-shadow: 0 2px 8px rgba(80, 80, 120, 0.04);
}
.user-message {
  background: linear-gradient(90deg, #4f8cff 0%, #6ee7b7 100%);
  color: #fff;
  align-self: flex-end;
}
.agent-message {
  background: #e0e7ef;
  color: #333;
  align-self: flex-start;
}

.chat-input {
  display: flex;
  padding: 14px 12px;
  border-top: 1px solid #eee;
  background: #f1f5f9;
}
.chat-input input {
  flex: 1;
  padding: 12px 14px;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  margin-right: 12px;
  font-size: 15px;
  background: #fff;
}
.chat-input input:focus {
  outline: none;
  border-color: #4f8cff;
  box-shadow: 0 0 0 2px rgba(79, 140, 255, 0.12);
}
.chat-input button {
  padding: 12px 22px;
  background: linear-gradient(90deg, #4f8cff 0%, #6ee7b7 100%);
  color: #fff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 15px;
  font-weight: bold;
  transition: background 0.2s;
}
.chat-input button:hover {
  background: linear-gradient(90deg, #2563eb 0%, #10b981 100%);
}
</style>
